package com.lawyer.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dyplsapi.model.v20170525.UnbindSubscriptionRequest;
import com.aliyuncs.dyplsapi.model.v20170525.UnbindSubscriptionResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.common.collect.Lists;
import com.lawyer.config.BaseConfigUrlBean;
import com.lawyer.config.WeiPayBean;
import com.lawyer.entity.RoomInfo;
import com.lawyer.entity.User;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.model.TokenInfo;
import com.lawyer.model.WxUserInfo;
import com.lawyer.repository.LawyerRepository;
import com.lawyer.repository.UserRepository;
import com.lawyer.service.PushService;
import com.lawyer.service.VirtualCallService;
import com.lawyer.uitls.WXUtils;

@RestController
@Api(tags = "测式专用")
@RequestMapping(value = "/test")
public class TestController {
	@Autowired
	private BaseConfigUrlBean baseConfigUrlBean;
	@Autowired
	private PushService pushService;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private LawyerRepository lawyerRepository;
	
	@Autowired
	private WeiPayBean WeiPayBean;
	@Autowired
	private VirtualCallService virtualCallService;
	
	private static String accessKeyId = "LTAI4FysHLsWsZ9cB8CzTA4o";
	private static String accessSecret = "3ERkTInHb5mmjOFGNbVaSbeoSj7sEl";
	
	protected final String SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=wx2de5288e1d9810c3&secret=a754c540848973bf56980595e004442c&grant_type=authorization_code&js_code=";

	@ApiOperation(httpMethod = "GET", value = "获取一个测式的tocken", notes = "获取一个测式的tocken")
	@RequestMapping(value = "/getToken", method = RequestMethod.GET)
	public HttpEntity<?> getToken() {
		RestTemplate restTemplate = new RestTemplate();
		MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
		headers.put("Content-Type", Lists.newArrayList(MediaType.APPLICATION_JSON_VALUE));
		User user = new User();
		user.setUsername("lcg");
		user.setPassword("lcg");

		ResponseEntity<TokenInfo> entity = restTemplate.exchange(baseConfigUrlBean.getLogin(), HttpMethod.POST, new HttpEntity<>(user), TokenInfo.class);
		TokenInfo info = entity.getBody();
		return new ResponseEntity<>(info, HttpStatus.OK);
	}
	@ApiOperation(httpMethod = "GET", value = "解除绑定", notes = "解除绑定")
	@RequestMapping(value = "/unbind", method = RequestMethod.GET)
	public HttpEntity<?> unbind(String subsId, String secretNo) {
		Message msg = new Message();
		UnbindSubscriptionResponse response = null;
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
		IAcsClient client = new DefaultAcsClient(profile);

		UnbindSubscriptionRequest request = new UnbindSubscriptionRequest();
		request.setPoolKey("FC100000147714030");
		//隐私号码。调用BindAXG等号码绑定接口时指定或自动分配的X号码。 
		request.setSecretNo(secretNo);
		//绑定关系ID,可以在控制台的号码管理 > 号码详情中查看绑定关系ID，或者在调用BindAxb等号码绑定API时查看返回参数中的SubsId。 
		request.setSubsId(subsId);

		try {
			response = client.getAcsResponse(request);
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			System.out.println("ErrCode:" + e.getErrCode());
			System.out.println("ErrMsg:" + e.getErrMsg());
			System.out.println("RequestId:" + e.getRequestId());
		}
		msg.setData(response);
		 return new ResponseEntity<>(msg, HttpStatus.OK);
	}
	
	@ApiOperation(httpMethod = "GET", value = "通过CID推送一个消息", notes = "给律师推送消息")
	@RequestMapping(value = "/push", method = RequestMethod.GET)
	public HttpEntity<?> push(String cid) {
		Message msg = new Message();
		RoomInfo info = new RoomInfo();
		info.setCreatedDate(new Date());
		info.setRoomId(112L);
		info.setUserId("我是用户id");;
		info.setLawyerId("我是律师id");
		info.setUserSig("我是签名");
		if (StringUtils.isNotEmpty(cid)) {
			pushService.pushToLawyer(cid, info);
			return new ResponseEntity<>(info, HttpStatus.OK);
		} else {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage("cid为空或无效");
			return new ResponseEntity<>(msg, HttpStatus.OK);
		}

	}
	@ApiOperation(httpMethod = "GET", value = "test", notes = "test")
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public HttpEntity<?> test() {
		Message msg = new Message();
		
		String encryptedData = "pt/QAb/bmnGU8ngO45NBs+GCXsYI/eD3oRmlVAxIbI9LmaGCrm4ekt9unZ3EHhPCvgtQ2RoKwRjkNaaWyOx80og/UeYo9XovxgNhaKjFWpuaFxKBCVXR/EtcJ+Y2TsqlZefLiA3+U9v/EJWGaZZGX79v+fxSbh0cjDVaaDUMH3gj25928AbAmFXh6huZ1sF1wun5A2i1mm4GaFsq/kfnUabY53QECbLJVvIVUZZOs77/8udjAkjAhOeEoZSgl/ap2S+bKItf3h0p1zDSuuNOtG8U2QClkOxjcWJMi3KEQxXxYoeSBDuqA5YQ5jo98aXzrf8Un4TLKvxXXHD1Fw7ZryJKL3iw8c5PjNygLNTVgpdkWFHLB3ooBJEqic2GruPYqiLLiRRdyoJpJy4+sfNZxA==";
		String sessionKey = "PXUdIXrLbyczLhQBKRIL+A==";
		String iv = "AIXfHrjEvLE+lEXWCEwtdg==";
		WxUserInfo userInfo = new WXUtils().getUserInfo(encryptedData, sessionKey, iv);
		
		User saveUser = new User();
		saveUser.setHeaderIco(userInfo.getAvatarUrl());
		saveUser.setId("lcg123456");
		saveUser.setNickName(userInfo.getNickName());
		saveUser.setEnabled(true);
		saveUser.setUsername("lcg123456");
		saveUser.setShareCount(0);
		saveUser.setBalance(0D);
		saveUser.setUsableTime(0L);
		saveUser.setIsCallPay(false);
		saveUser.setSessionKey(sessionKey);
		userRepository.save(saveUser);
		
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}


}
